#!/usr/bin/python3
#coding=utf-8

import os
import smtplib
import email
import sys
import time
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from log import *
from mysqlDB import *

today = datetime.datetime.now().strftime('%Y%m%d')
nowTime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# 当天23点30分30秒 退出程序
endTime = today + "233000"

remAccountApplyFileName = "rem_fut_account_apply/apply_list.txt"
appidAuthCodeFileName = "rem_fut_account_apply/appid_auth_code.txt"

class CEmail:
  def __init__(self, host="", port=12345, user="", pwd="",
               log=CLog(logName="send_email_server_rem_test_account_" + datetime.datetime.now().strftime('%Y%m%d')+".log", isPrint=True)):
    self.server = smtplib.SMTP()
    self.host = host
    self.port = port
    self.user = user
    self.pwd = pwd
    self.log = log
    if "" == self.host or "" == self.user:
      self.log.log("email param error host:" + self.host + " user:" + self.user)

  def sendEmail(self, addrSendTo="", msg=""):
    if 0 == len(addrSendTo):
      self.log.log("addr to send is empty can send message " + msg)
      return
    if "" == msg or len(msg) < 2:
      self.log.log("email to send failed, the message len must more then 10, message:" + msg)
      return

    try:
      self.server.connect(self.host, self.port)
      self.server.login(user=self.user, password=self.pwd)
      message = MIMEText(msg, "plain", "utf-8")
      # 主题
      message["Subject"] = "看穿式监管REM测试账户/API包/接入信息/demo"
      message["From"] = self.user
      message["To"] = addrSendTo
      self.server.sendmail(self.user, addrSendTo, message.as_string())
      self.server.quit()

    except smtplib.SMTPException as e:
      self.log.log(str(e))
      self.server.quit()


host = "smtp.exmail.qq.com"
port = 25
user = "test_support@shenglisoft.com"
pwd = "623240767qaZ"
#message="test email send"

msg1 = "您好！\n \
                        请重点关注一下我们的注意事项。\n \
                       （1）附件内容请至 https://gitee.com/korey_sparks/shengli_version_tool.git 获取\n \
                          1、REMTraderDemo.zip，交易DEMO程序\n \
                          2、rem_api_3.1.3.64.zip ，为API包，解压后的doc目录下有相关的文档；\n \
                          3、盛立REM私募常见问题，使用程序碰到的常见问题和解决方法；\n \
                          4、coll_rptr_1.0.0.7.zip，为看穿式监管客户端小工具，解压后有相关的使用说明；\n \
                          5、SKTProEESSetup_20190909_3.1.3.290.rar，为交易客户端界面化工具SKT\n \
                          6、盛立REM系统看穿式监管方案说明.pdf,为盛立看穿式监管方案说明及小工具使用说明等\n \
                       （2）REM测试账户信息：\n\
                           资金账号: "

firstPwd="                 初始密码：1\n\
                          "
msg2= "\
                      （3）测试环境连接信息\n\
                          行情前置：tcp://183.129.220.106:60006 \n\
                          交易前置：tcp://183.129.220.106:60000 \n\
                          查询前置：tcp://183.129.220.106:60001 \n\
                      （4）AppId和授权码：\n\
                          使用api接入的AppId:client，授权码:client_auth_code \n\
                          使用交易客户端界面化工具Skt的AppId:SKT，授权码:skt_auth_code \n\
\n\
                        ( 5 ) 注意事项： \n\
                          1、与之前相比，用户登录函数有一定的变化，prodInfo变为AppId,macAddr变为授权码。\n\
                          2、此测试环境只是用来测看穿式监管登录功能，纯模拟环境，7*24小时运行，无行情，下单全部成交的。\n\
                          3、司测试环境不支持udp下单功能。\n\
\n\
                           如有疑问请与我们联系，谢谢！\n\
                           微信：hzsljrrj  （杭州盛立金融软件，英文首字母）\n\
                           13372533274/13372552942 \n\
                           杭州盛立科技（开发）有限公司"
log=CLog(logName="send_email_server_rem_test_account_" + datetime.datetime.now().strftime('%Y%m%d') + ".log", isPrint=True)
db=CMySqlDB(log=log, dbHost="10.1.54.53", dbPort=3306, dbName="fut_one_config", dbUser="shengli", dbPwd="shengli0")
emailSMTPInstance=CEmail(host=host, port=port, user=user, pwd=pwd, log=log)

sqlQuery="select * from t_account_info"

def sendAccountInfo(emailAddr="", customerInfo="", logonIDCount=2):
  if ""==emailAddr or "@" not in emailAddr:
    log.log("email addr error ,cont send account info to " + emailAddr)
    return
  db.query("select * from t_account_info")
  accountInfo = db.getData()
  for accountLine in accountInfo:
    account = accountLine[0]
    desc = accountLine[1]
    if "no use"==desc:
      execSql="update t_account_info set account_desc = '" + emailAddr + "' where account_id = '" + account + "'"
      ret = db.exec(execSql)
      if ret :
        log.log("update account info success:" + execSql)
      else:
        log.log("update account info failed, cant send account info to customer " + emailAddr + "update sql:"+ execSql)
        return

      db.query("select max(1) from t_user_info")
      maxID = db.getData()

      for i in range(3, logonIDCount + 1):
        execSql = "REPLACE INTO t_user_info(user_id, login_id, md5_pwd, user_name, enabled, allow_mbl_query, \
                      allow_using_protocol, flowctrl_fusing, fusing_seconds, flowctrl_threshold, \
                      flowctrl_time, last_login_time, subscribe_type, create_time, active_time, last_update) \
        VALUES(" + str(maxID + i) + ",'" + (account + "0" + str(i)) + "', 'C4CA4238A0B923820DCC509A6F75849B', '', 'Y', 'N', 'Y', 'Y', 30, 300, 1, \
               '0000-00-00 00:00:00', 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00');"
        db.exec(execSql)
        execSql = "REPLACE INTO t_account_user_link (account_id, user_id) VALUES ('" + account +"'," + str(maxID + i)+ ");"
        db.exec(execSql)

      msg = msg1+ account +"\n"
      for i in range(1, logonIDCount + 1):
        msg = msg + "                 用户名" + str(i) + ":" + account + "0" + str(i) + "\n"
      msg =  msg + firstPwd+"\n" + msg2
      emailSMTPInstance.sendEmail(addrSendTo=emailAddr, msg=msg)
      return

  log.log("all account is in use, the count is " + len(accountInfo))
  log.log("there is no account can send to email " + emailAddr)


def getLastGitLibrary():
  # 确保要读取的文件存在
  os.system("ls rem_fut_account_apply > resulttxt")
  lsResult = open("resulttxt", mode="r")
  lines = lsResult.readlines()
  lsResult.close()
  if (len(lines) == 0):
    return False
  else:
    return True

# 获取老的记录
while True:
  if getLastGitLibrary():
    info = open(remAccountApplyFileName, mode="r")
    gitInfoVOri=info.readlines()
    info.close()
    log.log("load apply_list.txt, ori index is " + str(len(gitInfoVOri)))

    appidAuthInfo = open(appidAuthCodeFileName, mode="r")
    gitAppidInfoVOri=appidAuthInfo.readlines()
    appidAuthInfo.close()
    log.log("load appid_auth_code.txt, ori index is " + str(len(gitAppidInfoVOri)))
    log.log("now start to check apply_list.txt and appid_auth_code.txt, will do it 6 minutes one time")
    break
  else:
    os.system("git clone https://gitee.com/korey_sparks/rem_fut_account_apply.git")
    time.sleep(60)

while True:
  # 23:30退出监控
  timeNow = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  if timeNow >= endTime:
    break
  time.sleep(60 * 8)  # 10分钟一次
  os.system("rm  -rf rem_fut_account_apply")
  time.sleep(60)
  os.system("git clone https://gitee.com/korey_sparks/rem_fut_account_apply.git")
  time.sleep(60)
  if getLastGitLibrary():
    info = open(remAccountApplyFileName, mode="r")
    gitInfoV = info.readlines()
    desc = ""
    #没有新的提交
    if(len(gitInfoV) == len(gitInfoVOri)):
     log.log("there is no change info in apply_list from this update, continue")
    else:
      for index in range(0, len(gitInfoV) - len(gitInfoVOri)):
       desc = desc + gitInfoV[-1-index] + "\n"
      log.log("change info in apply_list from this update:" + desc)

    for lineIndex in range(len(gitInfoVOri), len(gitInfoV)):
      if "" == gitInfoV[lineIndex]:
       continue
      else: #至少1有元素
        msgs = gitInfoV[lineIndex].split(",", -1)
        # 只有一个字符串且包含"@" 判断为邮箱地址
        logonIDCount = 2
        if len(msgs) > 3 and (int(msgs[3]) < 10 and (int(msgs[3] > 2))):
          logonIDCount = int(msgs[3])
        if "@" in msgs[0]:
          desc = ""
          for index in range(1, len(msgs)):
            desc = desc + msgs[index] + " "
          sendAccountInfo(emailAddr=msgs[0], customerInfo=desc, logonIDCount=logonIDCount)
          gitInfoVOri = gitInfoV
    info.close()

###########################################################################################
    appidInfo = open(appidAuthCodeFileName, mode="r")
    gitAppidInfoV = appidInfo.readlines()
    # 没有新的提交
    if (len(gitAppidInfoV) == len(gitAppidInfoVOri)):
      log.log("there is no change info in appid_auth_code from this update, continue")
    else:
      desc = ""
      for index in range(0, len(gitAppidInfoV) - len(gitAppidInfoVOri)):
        desc = desc + gitAppidInfoV[-1 - index] + "\n"
      log.log("change info in appid_auth_code from this update:" + desc)

    for lineIndex in range(len(gitAppidInfoVOri), len(gitAppidInfoV)):
      if "" == gitAppidInfoV[lineIndex]:
        continue
      else: #至少1有元素
        msgs = gitAppidInfoV[lineIndex].split(",", -1)
        # 一个元素则认为是appid，自动加上默认authcode
        authCode = ""
        if len(msgs) == 1:
          authCode = msgs[0] + "_auth_code"
        else:
          authCode = msgs[1]
        confDB = CMySqlDB(log=log, dbHost="10.1.54.53", dbPort=3306, dbUser="shengli", dbPwd="shengli0", dbName="fut_one_config")
        confDB.exec("REPLACE INTO t_app_id_auth_code (app_id, auth_code, description, last_update_time) VALUES ('"+msgs[0]+"','" +authCode + "','',CURRENT_TIMESTAMP())")
        gitAppidInfoVOri = gitAppidInfoV
    appidInfo.close()
